/**
    Copyright (C) 2011  Alexander Vollmer

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jefb.web.controller;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Set;

import org.jefb.entity.RoleEntity;
import org.jefb.entity.UserEntity;
import org.jefb.service.IUserService;
import org.jefb.util.CryptographyUtil;
import org.jefb.util.JefbUtils;
import org.jefb.web.model.EntityModel;
import org.jefb.web.model.UserModel;
import org.jefb.web.util.ZKUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.SelectEvent;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;

@SuppressWarnings("serial")
@org.springframework.stereotype.Component
@Scope("prototype")
public class UserController extends EntityController<UserEntity> implements
		Serializable {
	
	//UI components
	protected Listbox assignedRolesListbox;
	protected Listbox unassignedRolesListbox;
	
	//services
	@Autowired
	private IUserService userService;
	@Autowired
	private UserModel userModel;

	private String[] colIds = new String[] { "username", "firstName",
			"lastName", "createTime" };	

	private enum Action {
		ADD, UPDATE
	}

	@Override
	protected String[] getColumnIds() {
		return colIds;
	}

	@Override
	protected UserEntity createNewEntityInstance() {
		return new UserEntity();
	}
	

	
	/* (non-Javadoc)
	 * @see org.jefb.web.controller.EntityController#doAfterCompose(org.zkoss.zk.ui.Component)
	 */
	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		unassignedRolesListbox.addEventListener(Events.ON_SELECT, new EventListener() {
			public void onEvent(Event event) throws Exception {
				if (event instanceof SelectEvent) {
					SelectEvent selectEvent = (SelectEvent) event;
					Set<?> selectedItems = selectEvent.getSelectedItems();
					Iterator<?> iterator = selectedItems.iterator();
					while(iterator.hasNext()){
						Object next = iterator.next();
						if (next instanceof Listitem) {
							Listitem listitem = (Listitem) next;
							RoleEntity value = (RoleEntity)listitem.getAttribute("roleEntity");
							userService.addRole(getModel().getSelectedEntity(), value);
							//userService.addRole(getModel().getSelectedEntity(), value);
//							getModel().getSelectedEntity().getUserRoles().add(value);
//							getCommonPersistenceService().updateEntity(getModel().getSelectedEntity());
						}
					}
				}
			}
		});
		assignedRolesListbox.addEventListener(Events.ON_SELECT, new EventListener() {
			public void onEvent(Event event) throws Exception {
				if (event instanceof SelectEvent) {
					SelectEvent selectEvent = (SelectEvent) event;
					Set<?> selectedItems = selectEvent.getSelectedItems();
					Iterator<?> iterator = selectedItems.iterator();
					while(iterator.hasNext()){
						Object next = iterator.next();
						if (next instanceof Listitem) {
							Listitem listitem = (Listitem) next;
							RoleEntity value = (RoleEntity)listitem.getAttribute("roleEntity");
							userService.deleteRole(getModel().getSelectedEntity(), value);
//							getModel().getSelectedEntity().getUserRoles().remove(value);
//							getCommonPersistenceService().updateEntity(getModel().getSelectedEntity());
						}
					}
				}
			}
		});
	}

	@Override
	public void onClick$addButton(Event e) {
		if (checkPassword(Action.ADD)) {
			super.onClick$addButton(e);
			resetModel();
		}
	}

	@Override
	public void onClick$updateButton(Event e) {
		if (checkPassword(Action.UPDATE)) {
			super.onClick$updateButton(e);
			resetModel();
		}
	}

	private boolean checkPassword(Action action) {

		switch (action) {
		case ADD:
			if (userModel.getPassword().equals(userModel.getConfirmPassword())) {
				getModel().getNewEntity().setPassword(
						CryptographyUtil.encodeSHA256(userModel.getPassword()));
				return true;
			} else {
				ZKUtils.showWarning("users.msg.passwords");
				return false;
			}
		case UPDATE:
			if (JefbUtils.isEmptyString(userModel.getPassword())
					&& JefbUtils.isEmptyString(userModel.getConfirmPassword())) {
				return true;
			} else if (userModel.getPassword().equals(
					userModel.getConfirmPassword())) {
				getModel().getSelectedEntity().setPassword(
						CryptographyUtil.encodeSHA256(userModel.getPassword()));
				return true;
			} else {
				ZKUtils.showWarning("users.msg.passwords");
				return false;
			}
		default:
			return false;
		}
	}

	public void setUserModel(UserModel userModel) {
		this.userModel = userModel;
	}

	public UserModel getUserModel() {
		return userModel;
	}

	@Override
	protected void resetModel() {
		super.resetModel();
		userModel.resetModel();
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public IUserService getUserService() {
		return userService;
	}

	@Override
	public EntityModel<UserEntity> getModel() {
		return userModel;
	}

}
